import { useTokenStore } from '@/stores/mytoken'
import request from '@/utils/request'

// 提取公共类型,T相当于一个形参(TS语法叫泛型,不具体的类型、动态类型)
// 默认T为string类型
type CommonReturn<T = string> = {
  success: boolean
  state: number
  message: string
  content: T
}
//用户登录请求参数类型
type LoginInfo = {
  username: string
  // 验证码可有可无
  // code?:string,
  password: string
}
// 用户登录返回数据类型(string为实参，传给CommonReturn<T>中的T的形参)
type LoginResult = CommonReturn<string>
// 用户请求登录
const login = (loginInfo: LoginInfo) => {
  return request({
    method: 'POST',
    // url:'/front/user/login',
    url: '/user/login',
    //以下不能有空格
    data: `username=${loginInfo.username}&password=${loginInfo.password}`
  })
}
/* 
    要求请求类型application/x-www.form-urlencoded, 需要把数据拼接为:属性1=值1&属性2=值2(不能有空格)
    data:`phone=${loginInfo.phone}&password=${loginInfo.password}`,
    要求请求类型application/json,只需要直接传对象
    data:loginInfo
 */
export default login
type UserInfo = CommonReturn<{
  isUpdatePassword: boolean
  portrait: string
  userName: string
}>
// 获取用户信息
export const getInfo = () => {
  console.log('获取用户信息接口')

  return request<UserInfo>({
    method: 'GET',
    url: '/front/user/getInfo'
  })
}
// 用户退出接口
export const logout = () => {
  return request({
    method: 'POST',
    url: '/front/user/logout'
  })
}
// 刷新token
type RToken = CommonReturn<string>

let promiseRT: Promise<any>
let isRefreshing = false //防止多次request请求，多次刷新token
export const refreshToken = () => {
  if (isRefreshing) {
    return promiseRT
  }
  isRefreshing = true
  promiseRT = request<RToken>({
    method: 'POST',
    url: '/front/user/refresh_token',
    params: {
      refreshToken: useTokenStore().token?.refresh_token
    }
  }).finally(() => {
    isRefreshing = false
  })

  return promiseRT
}

// 公共的类型
type Common<T> = {
  code: string
  data: T
  mesg: string
  time: string
}
// 每一个用户信息项的类型
type UserItem = {
  accountNonExpried: boolean
  accountNonlocked: boolean
  createTime: string
  credentialsNonExpired: boolean
  id: number
  isDel: boolean
  name: string
  password: string
  phone: string
  portrait: string | null
  // 注册时的IP地址
  regIp: string | null
  status: 'ENABLE' | 'DISABLE'
  updateTime: string
}
// 用户查询结果的类型
export type QueryResult = {
  current: number
  hitCount: boolean
  optimizeCountSql: boolean
  orders: any[]
  pages: number
  records: UserItem[]
  searchCount: boolean
  size: number
  total: number
}
// Partial每一个变量可以是可选项
export type QueryCondition = Partial<{
  currentPage: number
  pageSize: number
  phone: string
  userId: number
  startCreateTime: string
  endCreateTime: string
}>
// 获取用户列表信息,给QueryCondition一个空对象,没有Partial会报错
export const getUserPages = (queryCondition: QueryCondition = {}) => {
  return request<Common<QueryResult>>({
    method: 'POST',
    url: '/boss/user/getUserPages',
    data: queryCondition
  })
}
